#include <setjmp.h>
#include <signal.h>
#include <unistd.h>
#include "../ourhdr.h"

/***
 * 在一个捕捉其他信号的程序中调用sleep2
 **/

static jmp_buf env_alrm;

static void sig_alrm(int signo)
{
    longjmp(env_alrm, 1);
}

unsigned int sleep2(unsigned int nsecs)
{
    if(signal(SIGALRM, sig_alrm) == SIG_ERR)
    {
        return (nsecs);
    }
    if(setjmp(env_alrm) == 0)
    {
        alarm(nsecs);
        pause();
    }
    return (alarm(0));
}

static void sig_int(int);

int main(void)
{
    unsigned int unslept;
    if(signal(SIGINT,sig_int) == SIG_ERR)
    {
        err_sys("signal(SIGINT) error");
    }

    unslept = sleep2(20);
    printf("sleep2 returned: %u\n", unslept);
    exit(0);
}

static void sig_int(int signo)
{
    int i;
    volatile int j = 0;
    printf("\nsig_int starting\n");
    for(i=0;i<20000000;i++)
    {
        j +=  i*i;
    }
    printf("\nsig_int finished\n");
    return;
}